'use client';

import { useApp } from '@/contexts/AppContext';
import { products } from '@/lib/mockData';
import { useState, useEffect } from 'react';

export default function CartPage() {
  const { state, dispatch } = useApp();
  const [isCheckingOut, setIsCheckingOut] = useState(false);
  const [mounted, setMounted] = useState(false);

  useEffect(() => {
    setMounted(true);
  }, []);

  const updateQuantity = (productId: string, quantity: number) => {
    dispatch({ type: 'UPDATE_CART_QUANTITY', payload: { productId, quantity } });
  };

  const removeFromCart = (productId: string) => {
    dispatch({ type: 'REMOVE_FROM_CART', payload: productId });
  };

  const handleCheckout = async () => {
    setIsCheckingOut(true);
    // 跳转到结算页面
    setTimeout(() => {
      setIsCheckingOut(false);
      window.location.href = '/checkout';
    }, 500);
  };

  // 防止hydration不匹配，在客户端挂载前显示加载状态
  if (!mounted) {
    return (
      <div className="min-h-screen bg-gray-50 py-8">
        <div className="max-w-4xl mx-auto px-4">
          <div className="mb-8">
            <h1 className="text-3xl font-bold text-gray-800 mb-2">购物车</h1>
            <p className="text-gray-600">正在加载...</p>
          </div>
        </div>
      </div>
    );
  }

  if (state.cart.length === 0) {
    return (
      <div className="min-h-screen bg-gray-50 py-8">
        <div className="max-w-4xl mx-auto px-4">
          <div className="mb-8">
            <h1 className="text-3xl font-bold text-gray-800 mb-2">购物车</h1>
            <p className="text-gray-600">确认你的神秘盲盒，准备开启惊喜之旅</p>
          </div>
          <div className="text-center py-20">
            <div className="text-8xl mb-6">🛒</div>
            <h2 className="text-2xl font-bold text-gray-800 mb-4">购物车空空如也</h2>
            <p className="text-gray-600 mb-8">去商城看看有什么惊喜等着你吧！</p>
            <a
              href="/shop"
              className="bg-gradient-to-r from-yellow-400 to-orange-400 text-black font-bold py-3 px-8 rounded-lg hover:shadow-lg transition-shadow"
            >
              去逛逛盲盒商城
            </a>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-gray-50 py-8">
      <div className="max-w-4xl mx-auto px-4">
        {/* 页面标题 */}
        <div className="mb-8">
          <h1 className="text-3xl font-bold text-gray-800 mb-2">购物车</h1>
          <p className="text-gray-600">确认你的神秘盲盒，准备开启惊喜之旅</p>
        </div>

        <div className="grid lg:grid-cols-3 gap-8">
          {/* 购物车商品列表 */}
          <div className="lg:col-span-2 space-y-4">
            {state.cart.map((item) => (
              <div key={item.product.id} className="bg-white rounded-lg p-6 shadow-sm">
                <div className="flex items-center space-x-4">
                  {/* 商品图片 */}
                  <div className={`w-20 h-20 bg-gradient-to-br ${item.product.bgColor} rounded-lg flex items-center justify-center flex-shrink-0`}>
                    <span className="text-2xl">📦</span>
                  </div>

                  {/* 商品信息 */}
                  <div className="flex-1">
                    <h3 className="font-semibold text-gray-800 mb-1">{item.product.name}</h3>
                    <p className="text-sm text-gray-600 mb-2">{item.product.description}</p>
                    <p className="text-sm text-orange-600">估值: {item.product.originalValue}</p>
                  </div>

                  {/* 价格和数量 */}
                  <div className="text-right">
                    <div className="text-xl font-bold text-gray-800 mb-2">¥{item.product.price}</div>
                    
                    {/* 数量控制 */}
                    <div className="flex items-center space-x-2 mb-2">
                      <button
                        onClick={() => updateQuantity(item.product.id, item.quantity - 1)}
                        className="w-8 h-8 rounded-full border border-gray-300 flex items-center justify-center hover:bg-gray-50"
                        disabled={item.quantity <= 1}
                      >
                        -
                      </button>
                      <span className="w-8 text-center">{item.quantity}</span>
                      <button
                        onClick={() => updateQuantity(item.product.id, item.quantity + 1)}
                        className="w-8 h-8 rounded-full border border-gray-300 flex items-center justify-center hover:bg-gray-50"
                      >
                        +
                      </button>
                    </div>

                    {/* 删除按钮 */}
                    <button
                      onClick={() => removeFromCart(item.product.id)}
                      className="text-red-500 hover:text-red-700 text-sm"
                    >
                      移除
                    </button>
                  </div>
                </div>
              </div>
            ))}
          </div>

          {/* 订单摘要 */}
          <div className="lg:col-span-1">
            <div className="bg-white rounded-lg p-6 shadow-sm sticky top-24">
              <h3 className="font-semibold text-gray-800 mb-4">订单摘要</h3>
              
              <div className="space-y-3 mb-6">
                <div className="flex justify-between">
                  <span className="text-gray-600">商品数量</span>
                  <span className="font-medium">{state.cartCount} 个</span>
                </div>
                <div className="flex justify-between">
                  <span className="text-gray-600">商品总计</span>
                  <span className="font-medium">¥{state.cartTotal.toFixed(2)}</span>
                </div>
                <div className="flex justify-between">
                  <span className="text-gray-600">运费</span>
                  <span className="font-medium text-green-600">免费</span>
                </div>
                <div className="border-t pt-3">
                  <div className="flex justify-between text-lg font-bold">
                    <span>总计</span>
                    <span className="text-orange-600">¥{state.cartTotal.toFixed(2)}</span>
                  </div>
                </div>
              </div>

              {/* 优惠券 */}
              <div className="mb-6">
                <div className="flex space-x-2">
                  <input
                    type="text"
                    placeholder="输入优惠券代码"
                    className="flex-1 px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-orange-500 focus:border-transparent"
                  />
                  <button className="px-4 py-2 bg-gray-100 text-gray-700 rounded-lg hover:bg-gray-200">
                    使用
                  </button>
                </div>
              </div>

              {/* 结算按钮 */}
              <button
                onClick={handleCheckout}
                disabled={isCheckingOut}
                className="w-full bg-gradient-to-r from-yellow-400 to-orange-400 text-black font-bold py-3 px-6 rounded-lg hover:shadow-lg transition-shadow disabled:opacity-50 disabled:cursor-not-allowed"
              >
                {isCheckingOut ? '处理中...' : '立即结算'}
              </button>

              {/* 安全提示 */}
              <div className="mt-4 text-xs text-gray-500 text-center">
                🔒 支付安全由第三方保障
              </div>
            </div>
          </div>
        </div>

        {/* 推荐商品 */}
        <div className="mt-12">
          <h3 className="text-xl font-bold text-gray-800 mb-6">猜你喜欢</h3>
          <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
            {products.slice(0, 4).map((product, index) => (
              <div key={index} className="bg-white rounded-lg p-4 shadow-sm text-center">
                <div className={`w-16 h-16 bg-gradient-to-br ${product.bgColor} rounded-lg flex items-center justify-center mx-auto mb-3`}>
                  <span className="text-xl">📦</span>
                </div>
                <h4 className="font-medium text-gray-800 mb-2">{product.name}</h4>
                <p className="text-orange-600 font-bold">¥{product.price}</p>
                <a 
                  href={`/product/${product.id}`}
                  className="mt-2 inline-block text-sm text-orange-600 hover:text-orange-700"
                >
                  查看详情
                </a>
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}